package com.xavier.dong.nacos.grpc.server.interceptor;

import com.xavier.dong.nacos.grpc.server.common.Constants;
import io.grpc.*;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.interceptor.GrpcGlobalServerInterceptor;

import java.util.Objects;

/**
 * Example {@link ServerInterceptor} that logs all called methods. In this example it is added to Spring's application
 * context via {@link GlobalInterceptorConfiguration}, but is also possible to directly annotate this class with
 * {@link GrpcGlobalServerInterceptor}.
 */
//@GrpcGlobalServerInterceptor
@Slf4j
public class LogGrpcInterceptor implements ServerInterceptor {

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
            ServerCall<ReqT, RespT> serverCall,
            Metadata metadata,
            ServerCallHandler<ReqT, RespT> serverCallHandler) {

        log.info(serverCall.getMethodDescriptor().getFullMethodName());

        return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
                serverCallHandler.startCall(serverCall, metadata)) {
            /**
             * onHalfClose is called on the same thread that calls the service handler.
             */
            @Override
            public void onHalfClose() {
                String remoteIpAddress =
                        Objects.requireNonNull(serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)).toString();
                Constants.IP_ADDRESS_THREAD_LOCAL.set(remoteIpAddress);
                super.onHalfClose();
            }
        };
    }


}